﻿namespace AY38910
{
    using System;
    using System.IO.Ports;

    public class SerialHelper : IDisposable
    {
        private readonly SerialPort serialPort;

        public SerialHelper(string portName)
        {
            this.serialPort = new SerialPort(portName, 115200)
            {
                //Encoding = Encoding.UTF8,
                //WriteBufferSize = 8192
            };

            this.serialPort.Open();
        }

        public void Write(byte[] bytes)
        {
            this.serialPort.Write(bytes, 0, bytes.Length);
        }

        public static string[] ListPortNames()
        {
            return SerialPort.GetPortNames();
        }

        public void Send(PsgAction action, byte data)
        {
            var bytes = new[] { Convert.ToByte((int)action), data };
            this.serialPort.Write(bytes, 0, bytes.Length);
        }

        #region IDisposable Members

        public void Dispose()
        {
            if (this.serialPort == null)
            {
                return;
            }

            if (this.serialPort.IsOpen)
            {
                this.serialPort.Close();
            }

            this.serialPort.Dispose();
        }

        #endregion
    }
}
